merDetailController = BaseController.extend({
	template: 'merchantDetail',
	center: '商家详情',
	left: '',
	right: '<a href="#" class="link" id="collection" style="margin-right:2px"><i class="iconfont icon-shoucang" style="font-size:1.4rem"></i></a>',
	//headerTransparent: true,
	mainView: 'merchant',
	subHandle: false,
	ntime: new ReactiveVar(),
	isc:true,
	is_swiper:new ReactiveVar(0),
	c_user_id:new ReactiveVar(),
	waitOn: function () {
		this.subscribeHandleDict = {};
		let self = this;
		//this.user_id = 0;
		if(localStorage.lat && localStorage.lat){
			this.slat = parseFloat(localStorage.lat);
			this.slng = parseFloat(localStorage.lng);
		}else{
			this.slat = 31.785381;
			this.slng = 117.242346;
		}
		this.get('user/get-time',{}).then(function(res){
			self.ntime.set(res.data);
		}, function (err) {

		})
		Tracker.autorun(function () {
			self.user = self.currentUser();
			if(self.user){
				self.user_id = self.user.id;
				self.c_user_id.set(self.user.id);
			}
			return [
				Meteor.subscribe('merchant', { id: parseInt(self.params.id) }, {}, function () { }),
				Meteor.subscribe('goods', { merchant_id: parseInt(self.params.id) }, { limit: 5 }, function () { }),
				Meteor.subscribe('comments', { merchant_id: parseInt(self.params.id)}, {fields:{user:true,id:true,stars:true,context:true},limit: 5 }, function () { }),
				Meteor.subscribe('collections', { merchant_id: parseInt(self.params.id), user_id: parseInt(self.c_user_id.get()) },function(){
					if(Collections.find({merchant_id:parseInt(self.params.id),user_id:parseInt(self.c_user_id.get())}).count() > 0){
						$('.right').find('.icon-shoucang').css('color','#ff0000')
					}
				})
			];

		});
	},
	onRendered: function (self) {
		self.isc = true;
		setTimeout(function(){
			var myApp = new Framework7();
			var mySwiper = myApp.swiper('.swiper-container', {
				pagination: ".swiper-pagination",
				speed: 400,
				spaceBetween: 1
			});
		},1000)
		$('.right').on('click', '#collection', function () {
			var user_id = self.c_user_id.get();
			self.post('user/collection',{merchant_id:self.params.id,user_id:user_id}).then(function(res){
				if(res.data){
					$('.right').find('.icon-shoucang').css('color','#ff0000')
					self.isc = false;
					//$('.right').find('#collection').remove();
				}
			},function(err){

			})
		})
	},
	data: function () {
		let self = this;
		return {
			md: function () {
				var t = self.ntime.get();
				let dt = merchant.findOne({ id: parseInt(self.params.id) });
				if (dt != 'undefined' && dt != undefined && t != 'undefined' && t != undefined ) {
					var loc = self.gtlng(self.slat,self.slng,dt.location.coordinates[1],dt.location.coordinates[0]);
					if (Math.round(loc / 1000 * 100) / 100 > 1000) {
						dt.jl = '';
					} else {
						dt.jl = Math.round(loc / 1000 * 100) / 100 + 'km';
					}
					dt.idle = {};
					dt.idle_day = [];
					for(var i in dt.idles){
						if(dt.idles[i].d == t.w){
							dt.idle_day = dt.idles[i].idle;
						}
						if(typeof(dt.idles[i].d) != 'undefined' && dt.idles[i].d == t.w){
							for(var j in dt.idles[i].idle){
								if(dt.idles[i].idle[j].start_second < t.t && dt.idles[i].idle[j].end_second > t.t){
									dt.idle = dt.idles[i].idle[j];
								}
							}
						}
					}
				}
				// if(typeof(dt) != 'undefined'){
				// 		self.is_swiper.set(1);
				// }
				return dt;
			},
			goodsNum:function(){
				var gnum = goods.find({merchant_id: parseInt(self.params.id)}).count();
				return gnum > 3;
			},
			goods: goods.find({merchant_id: parseInt(self.params.id)}, { limit: 3 }).fetch(),
			comments: Comments.find({}, { limit: 4 }).fetch()
		}
	}
})


merController = BaseController.extend({
	template: 'merchant',
	center: '<div class="searchbar-input"><input type="search" id="search_keywords" placeholder="请输入搜索关键词" class=""><a href="#" class="searchbar-clear"></a></div>',
	mainView: 'merchant_list',
	keywords: '',
	lng: false,
	merchant_selector: new ReactiveVar({}),
	merchant_sort: new ReactiveVar({}),
	merchantsList: new ReactiveVar([]),
	ntime: new ReactiveVar(),
	sid:new ReactiveVar(0),
	waitOn: function () {
		this.limit = 200;
		this.mlist_selectors = { state: 'opened' };
		this.mlist_selector = {};
		this.sorts = { id: -1 };
		this.s = {};
		//this.subscribeHandleDict={};
		let self = this;
		if(localStorage.lat){
			this.slat = parseFloat(localStorage.lat);
			this.slng = parseFloat(localStorage.lng);
		}else{
			this.slat = 31.785381;
			this.slng = 117.242346;
		}
		this.get('user/get-time',{}).then(function(res){
			self.ntime.set(res.data);
		}, function (err) {
			console.log(err)
		})
		//localStorage.siteId = 2;
		if (this.params.query.cate_id) {
			if (typeof(localStorage.siteId) != 'undefined') {
				this.sid.set(localStorage.siteId);
				this.site_id = localStorage.siteId;
				this.mlist_selectors = { cate_id: parseInt(this.params.query.cate_id), site_ids: parseInt(this.site_id) };
			} else {
				this.mlist_selectors = { cate_id: parseInt(this.params.query.cate_id) };
			}
			this.mlist_selector = _.clone(this.mlist_selectors);
			this.s = _.clone(this.mlist_selectors);
		} else {
			if (typeof(localStorage.siteId) != 'undefined') {
				this.sid.set(localStorage.siteId);
				this.site_id = localStorage.siteId;
				this.mlist_selectors = { site_ids: parseInt(this.site_id) };
			} else {
				this.mlist_selectors = {};
			}
			this.mlist_selector = _.clone(this.mlist_selectors);
			this.s = _.clone(this.mlist_selectors);
		}
		this.merchant_selector.set(this.mlist_selector);
		Meteor.subscribe('merchant', this.mlist_selector, {
			sort: { id: -1 },
			limit: this.limit ,
			fields:{
				list_image:true,
				id:true,
				name:true,
				month_order_count:true,
				labels:true,
				cate:true,
				site_name:true,
				idle:true,
				coupons:true,
				idles:true,
				idle_day:true,
				location:true,
				cate_id:true,
				site_ids:true,
				sites:true
			}});
		},
		onRendered: function (self) {
			Template.body.view = null;
			Template.body.renderToDocument();
			self.keywords = '';
			$('.center').bind('input propertychange', function () {
				var str = $(this).find('#search_keywords').val();
				str = str.replace(/ /g, '');
				if (str == self.keywords) return;
				if (str.length > 0) {
					self.merchant_sort.set({ sort: { id: -1 } });
					self.merchant_selector.set({ $or: [{ name: str }, { labels: str }] });
				} else {
					self.merchant_sort.set({ sort: { id: -1 } });
					self.merchant_selector.set({});
				}
				self.keywords = str;
			});
		},
		data: function () {
			var self = this;
			return {
				//scroll:'infinite-scroll',
				notEmpety: function () {
					return merchant.find(self.merchant_selector.get()).count() > 0;
				},
				merList: function () {
					var data = merchant.find(self.merchant_selector.get(),self.merchant_sort.get()).fetch();
					var t = self.ntime.get();
					console.log(self.slat)
					if(t != 'undefined' && t != undefined){
						for (var i in data) {
							var loc = self.gtlng(self.slat,self.slng,data[i]['location']['coordinates'][1],data[i]['location']['coordinates'][0]);
							if (Math.round(loc / 1000 * 100) / 100 > 1000) {
								data[i].jl = '';
							} else {
								data[i].jl = Math.round(loc / 1000 * 100) / 100 + 'km';
							}
							if(data[i].sites){
								var ssid = self.sid.get();
								for(var g in data[i].sites){
									if(typeof(data[i].sites[g]) != 'undefined' && typeof(data[i].sites[g].name) != 'undefined'){
										data[i].site_name = data[i].sites[g].name;
										if(ssid){
											if(ssid == data[i].sites[g].id){
												data[i].site_name = data[i].sites[g].name;
												break;
											}
										}
									}
								}
							}
							data[i].idle = {};
							for(var j in data[i].idles){
								if(typeof(data[i].idles[j].idle) != 'undefined' && data[i].idles[j].d == t.w){
									for(var k in data[i].idles[j].idle){
										if(data[i].idles[j].idle[k].start_second < t.t && data[i].idles[j].idle[k].end_second > t.t){
											data[i].idle = data[i].idles[j].idle[k];
										}
									}
								}
							}
						}
					}
					return data;
				}
			}
		},
		events: function () {
			let self = this;
			return {
				'click #zh-sort': function (e) {
					self.lng = false;
					self.merchant_selector.set(self.mlist_selector);
					self.merchant_sort.set({ sort: { id: -1 } });
				},
				'click #buy-sort': function (e) {
					self.lng = false;
					self.merchant_selector.set(self.mlist_selector)
					self.merchant_sort.set({ sort: { month_order_count: -1 } });
				},
				'click #jl-sort': function (e) {
					self.lng = true;
					self.s.location = { $near: { $geometry: { type: 'Point', coordinates: [self.slng, self.slat] } } };
					self.merchant_selector.set(self.s);
					self.merchant_sort.set({});
				}
			}
		}
	})

	bossController = BaseController.extend({
		template: 'boss',
		center: '商家故事',
		mainView: 'boss',
		waitOn: function () {
			let self = this;
			Meteor.subscribe('merchant', { id: parseInt(this.params.query.merchant_id) }, {}, function () {
				return self.ready();
			});
		},
		data: function () {
			var self = this;
			return {
				merDetail: function () {
					return merchant.findOne({ id: parseInt(self.params.query.merchant_id) });
				}
			}
		}
	})

	idleController = BaseController.extend({
		template: 'idle',
		center: '',
		left: '闲惠规则详情',
		mainView: 'idle',
		waitOn: function () {
			let self = this;
			Meteor.subscribe('merchant', { id: parseInt(this.params.query.merchant_id) }, {}, function () {
				return self.ready();
			});
		},
		data: function () {
			var self = this;
			return {
				merDetail: function () {
					return merchant.findOne({ id: parseInt(self.params.query.merchant_id) });
				}
			}
		}
	})

	mdetailController = BaseController.extend({
		template: 'mdetail',
		center: '',
		left: '详情',
		mainView: 'mdetail',
		waitOn: function () {
			let self = this;
			Meteor.subscribe('merchant', { id: parseInt(this.params.query.merchant_id) }, {}, function () {
				return self.ready();
			});
		},
		data: function () {
			var self = this;
			return {
				merDetail: function () {
					return merchant.findOne({ id: parseInt(self.params.query.merchant_id) });
				}
			}
		}
	})

	Template.merchant.onDestroyed(function () {

	});


	merchantMapController = BaseController.extend({
		template: 'merchantMap',
		center: '地图导航',
		right: '',
		mainView: 'merchantMap',
		subHandle: false,
		waitOn: function () {
			let self = this;
		},
		onRendered: function (self) {
			var umap = {
				lng: '',
				lat: ''
			};
			var mmap = {
				lng: this.params['lng'],
				lat: this.params['lat']
			};
			var map, geolocation;
			//加载地图，调用浏览器定位服务
			map = new AMap.Map('container', {
				resizeEnable: true
			});
			map.plugin('AMap.Geolocation', function () {
				geolocation = new AMap.Geolocation({
					enableHighAccuracy: true,//是否使用高精度定位，默认:true
					timeout: 3000,          //超过10秒后停止定位，默认：无穷大
					buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
					buttonPosition: 'RB'
				});
				map.addControl(geolocation);
				geolocation.getCurrentPosition();
				AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
				AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
			});

			//解析定位结果
			function onComplete(data) {
				umap.lng = data.position.lng;
				umap.lat = data.position.lat;
				map.plugin('AMap.Walking', function () {
					//步行导航
					var walking = new AMap.Walking({
						map: map
					});
					//根据起终点坐标规划步行路线
					walking.search([data.position.lng, data.position.lat], [mmap.lng, mmap.lat]);
				});

			}
			//解析定位错误信息
			function onError(data) {
				document.getElementById('tip').innerHTML = '定位失败';
			}
			function gotoMap() {
				window.location.href = "http://uri.amap.com/navigation?from=" + umap.lng + "," + umap.lat + ",起点&to=" + mmap.lng + "," + mmap.lat + ",终点&mode=walk&src=mypage&coordinate=gaode&callnative=0";
			}
		},
		data: function () {
			let self = this;
			return {

			}
		}
	})
